<template>
  <div>
    <div class="mask" @click="closePopup(false)"></div>
    <div class="edit_box" id="change_width" v-loading="loading">
      <div class="box_head">
        <p>下单</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">

        <div>
          <div class="line">
            <span class="lab"><i class="mark_icon">*</i>用户：</span>
            <userSelect @listenToUser="getUserId" :uId="userId" v-if="!$route.query.userId"/>
            <div v-else>{{ $route.query.username }}</div>
          </div>
          <div class="line" v-if="userId !== ''">
            <div class="g-mt-10">
              <a class="common_btn el-icon-delete" @click="clearNum()"></a>
              <a class="common_btn el-icon-circle-plus-outline" @click="addProNum()"></a>
            </div>
          </div>
          <div v-if="userId !== ''">
            <div v-for="(link,index) in proNum" :key="index" class="input-box g-mb-10" id="link"
                 @mouseenter="showDel(index)" @mouseleave="delNum=null" style="margin-top: 30px;">
              <div class="input_box">
                <div :class="errIndex === index && errKey === 'productId' ? 'error_border select_box' : 'select_box'"
                     ref="input">
                  <el-select
                    filterable
                    ref="linkName"
                    :popper-append-to-body="false"
                    v-model="link.productId"
                    @change="getProductInfo($event,index)"
                    placeholder="请选择商品" @focus="getIndex($event,index)">
                                <span v-if="link.productId === ''">
                                <el-option
                                  v-for="(item,index) in list"
                                  :key="index"
                                  :label="item.name"
                                  :value="item.id">
                                </el-option>
                                  </span>
                    <span v-else>
                                <el-option
                                  v-for="(item,index) in finalProductList"
                                  :key="index"
                                  :label="item.name"
                                  :value="item.id">
                                </el-option>
                                  </span>
                  </el-select>
                </div>

                <i class="delSingle el-icon-remove-outline" @click="delSingleInput(index)"></i>
              </div>
              <div class="sonData list_item">
                <div>
                  <el-input :class="errIndex === index && errKey === 'numbers' ? 'error_border' : ''" placeholder="数量"
                            type="number"
                            min="0"
                            v-model="proNum[index].numbers">
                    <template slot="prepend">数量</template>
                  </el-input>
                </div>
                <div>
                  <el-input :class="errIndex === index && errKey === 'returnNumber' ? 'error_border' : ''"
                            placeholder="空桶数" type="number" min="0"
                            v-model="proNum[index].returnNumber">
                    <template slot="prepend">空桶数</template>
                  </el-input>
                </div>
                <div>
                  <el-input placeholder="已使用额度"
                            :class="errIndex === index && errKey === 'usedAuthNumber' ? 'error_border' : ''"
                            type="number"
                            min="0"
                            v-model="proNum[index].usedAuthNumber">
                    <template slot="prepend">已使用额度</template>
                  </el-input>
                </div>
                <div>
                  <el-input placeholder="授权额度"
                            :class="errIndex === index && errKey === 'authNumber' ? 'error_border' : ''" type="number"
                            min="0"
                            v-model="proNum[index].authNumber">
                    <template slot="prepend">授权额度</template>
                  </el-input>
                </div>
                <div>
                  <el-input placeholder="抵押数量" type="number" min="0"
                            :class="errIndex === index && errKey === 'pledgeNumber' ? 'error_border' : ''"
                            v-model="proNum[index].pledgeNumber">
                    <template slot="prepend">抵押数量</template>
                  </el-input>
                </div>
                <div>
                  <el-input placeholder="抵押金额" type="number" min="0"
                            :class="errIndex === index && errKey === 'pledgeMoney' ? 'error_border' : ''"
                            v-model="proNum[index].pledgeMoney">
                    <template slot="prepend">抵押金额</template>
                  </el-input>
                </div>
              </div>

            </div>
          </div>
        </div>
        <p class="error_line">{{ tipText }}</p>
      </div>

      <div class="box_foot">
        <span @click="closePopup(false)">取消</span>
        <span @click="judgeProNum">确定</span>
      </div>

    </div>
  </div>
</template>

<script>

import userSelect from '../../../components/user/index.vue'
import {listAllData} from "@/api/config/product";
import {getProductNumber, createData} from "@/api/data/user/change";

export default {
  components: {
    userSelect
  },
  data() {
    return {
      loading: false,
      tipText: '',
      userId: '',
      finalProductList: [],
      isFinal: false,
      list: [],
      proNum: [{
        productId: '',
        numbers: '',
        returnNumber: '',
        usedAuthNumber: 0,
        authNumber: '',
        pledgeNumber: '',
        pledgeMoney: ''
      }],
      delNum: null,
      errIndex: undefined,
      errKey: undefined,
    }
  },
  mounted() {
    if (this.$route.query.userId) {
      this.userId = parseInt(this.$route.query.userId);
    }
  },
  methods: {
    getUserId(e) {
      this.userId = e;
    },

    getProduct(data) {
      let queryParams = {
        // userId: this.userId
      }
      if (data) {
        queryParams.productIds = data;
      }
      listAllData(queryParams).then((res) => {
        this.list = res ? res : [];
        if (!this.isFinal) {
          this.finalProductList = res ? res : [];
          this.isFinal = true;
        }
      })
    },

    //获取当前商品的数据
    getProductInfo(id, index) {
      let params = {
        userId: this.userId,
        productId: id
      }
      getProductNumber(params).then((res) => {
        if (res) {
          this.proNum[index].authNumber = res.authNumber;
          this.proNum[index].numbers = res.numbers;
          this.proNum[index].pledgeMoney = res.pledgeMoney;
          this.proNum[index].pledgeNumber = res.pledgeNumber;
          this.proNum[index].returnNumber = res.returnNumber;
          this.proNum[index].usedAuthNumber = res.usedAuthNumber;
        }
      })
    },

    getIndex(e, index) {
      this.errIndex = '';
      this.tipText = '';
      this.proNum[index].productId = '';
      //重新获取当前的数据
      this.getNewAllProduct();
    },

    getNewAllProduct() {
      // 重新获取列表
      let arr = []
      this.proNum.forEach((item, index) => {
        if (item.productId !== '') {
          arr.push(item.productId)
        }
        return arr
      })
      arr = arr.join(',')
      this.getProduct(arr);
    },

    closePopup(refresh) {
      this.$emit('listenToChild', refresh)
    },

    judgeProNum() {
      let that = this;
      let proLen = that.proNum.length - 1;
      let proLenth = that.proNum.length;
      for (let i = 0; i < proLenth; i++) {
        let data = that.proNum[i];
        let textArr = {
          productId: '商品',
          numbers: '数量',
          returnNumber: '空桶数',
          usedAuthNumber: '已使用额度',
          authNumber: '授权额度',
          pledgeNumber: '抵押数量',
          pledgeMoney: '抵押金额'
        }
        let auth = '';
        let usedAuth = '';
        for (let key in data) {
          if (data[key] === '') {
            that.errIndex = i;
            that.errKey = key;
            let keyName = textArr[key]
            that.tipText = `请输入${keyName}!`;
            return;
          }
          auth = data['authNumber']
          usedAuth = data['usedAuthNumber']
          if (parseFloat(usedAuth) > parseFloat(auth)) {
            that.tipText = `授权额度需大于已使用额度!`;
            return;
          }
        }
        if (proLen === i) {
          that.errIndex = '';
          that.errKey = '';
          that.tipText = '';
          that.createUserOrder();
        }
      }
    },

    createUserOrder() {
      this.loading = true;
      let param = {
        userId: this.userId,
        detailInsertVos: this.proNum
      }
      createData(param).then(res => {
        this.$message.success({
          message: '操作成功',
          duration: 1500
        });
        this.closePopup(true);
        this.loading = false;
      }).catch((e) => {
        this.loading = false;
      })
    },

    deleteProduct(index) {
      let num = this.proNum[index].numbers;
      this.proNum[index].numbers = parseFloat(num) <= 1 ? 1 : parseFloat(num) - 1;
    },

    addProduct(index) {
      let limit = document.getElementById('num' + index).innerHTML;
      let max = limit ? parseFloat(limit) : 0;
      let num = parseFloat(this.proNum[index].numbers)
      this.proNum[index].numbers = !max || num < max ? num + 1 : num;
    },

    /*添加*/
    addProNum() {
      let cope = {
        productId: '',
        numbers: '',
        returnNumber: '',
        usedAuthNumber: 0,
        authNumber: '',
        pledgeNumber: '',
        pledgeMoney: ''
      };
      this.proNum.push(cope);
      this.tipText = '';
    },

    /*清除*/
    clearNum() {
      this.proNum = [];
      for (let i in this.$refs.input) {
        this.$refs.input[i].className = ''
      }
      let cope = {
        productId: '',
        numbers: '',
        returnNumber: '',
        usedAuthNumber: 0,
        authNumber: '',
        pledgeNumber: '',
        pledgeMoney: ''
      };
      this.proNum.push(cope);
      this.tipText = '';
    },

    // 单个删除
    delSingleInput(index) {
      this.proNum.splice(index, 1);
      this.tipText = '';
    },

    showDel(index) {
      this.delNum = index + 1;
      /*只有一条的时候，不加删除文字，可清空*/
      if (this.proNum.length == 1) {
        this.delNum = null
      }
    },
  }
}
</script>
<style>
.list_item .el-input-group__prepend {
  width: 80px !important;
  padding: 0 10px !important;
}
</style>
<style scoped>
#change_width {
  /*width:700px;*/
}

.sonData {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.sonData > div {
  width: 40%;
  margin-top: 5px;
}

.sonData > div:nth-of-type(2n) {
  margin-left: 20px;
}

.input_box {
  display: flex;
  align-items: center;
  position: relative;
}

.line .link-input {
  line-height: 36px;
  border-radius: 4px;
  outline: none;
}

* {
  box-sizing: border-box;
}

.g-mb-10 {
  margin-bottom: 10px;
}

.g-ml-15 {
  margin-left: 15px;
}

a {
  text-decoration: none;
}

.link-txt {
  margin-right: 12px;
  width: 15px;
  float: left;
}

.link-input {
  width: 250px;
  height: 36px;
  background-color: #ffffff;
  border-radius: 2px;
  border: solid 1px #dcdcdc;
  padding-left: 15px;
  float: left;
  display: block;
  font-size: 14px;
  padding-right: 35px;
}

.common_btn {
  font-size: 24px;
  cursor: pointer;
  color: #6687f9;
  margin-right: 5px;
}

.delSingle {
  position: absolute;
  top: 10px;
  right: 18px;
  cursor: pointer;
  font-size: 22px;
  color: #e40000;
}

.num_box {
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  overflow: hidden;
  margin-left: 30px;
}

.minus_btn, .plus_btn {
  width: 34px;
  display: inline-block;
  height: 34px;
  line-height: 34px;
  text-align: center;
  cursor: pointer;
}

.minus_btn i, .plus_btn i {
  color: #6687f9;
}

.minus_btn {
  border-right: 1px solid #DCDFE6;
}

.plus_btn {
  border-left: 1px solid #DCDFE6;
}

.lose {
  color: #DCDFE6 !important;
}

.num_show {
  max-width: 80px;
  min-width: 40px;
  line-height: 34px;
  text-align: center;
  border: none;
  outline: none;
}

.limit_box {
  margin-top: 10px;
  font-size: 14px;
  color: #6687f9;
}

.specail_error {
  padding-left: 0;
  margin-top: 30px;
}
</style>

